import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ViewUI from 'view-design';
import VueResource from 'vue-resource'
import './index.css'

import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
import GlobalFun from './components/globalFun';
import 'view-design/dist/styles/iview.css';
import './assets/style/public.css'
import './assets/style/out.css'
import './assets/alifont/iconfont.css'
import './assets/alifont/demo.css'
import VueContextMenu from 'vue-contextmenu'
import UmyUi from 'umy-ui'
import 'umy-ui/lib/theme-chalk/index.css' // 引入样式
import {sessionStorage} from './common/cacheUtils.js'
import {useWebSocket} from './common/websocket.js'
import Common from './common/user'
import $ from "jquery";
import twoLevelOrg from "@/components/twoLevelOrg";
import companySelect from "@/components/company-select";
import downloadButton from "@/components/download-button";

Vue.prototype.useWebSocket = useWebSocket
Vue.use(VueQuillEditor)
Vue.use(VueContextMenu)
// import 'swiper/css/swiper.css'
// import VueAwesomeSwiper from 'vue-awesome-swiper'
Vue.use(Viewer)

Vue.config.productionTip = false
Vue.use(ViewUI);
Vue.use(VueResource);
// Vue.use(VueAwesomeSwiper, /* { default global options } */)
Vue.use(GlobalFun);
Vue.use(UmyUi)

Vue.mixin({
    beforeRouteLeave: function (to, from, next) {
        if (!(
            (to.name == "ptwTicketRecordView" && from.name == "ptwRecord")
            || from.name == "taskList"  //流程管理页面不刷新
		    || ['greenMine','greenFactory','greenPark','greenSupplyChain',
			    'specialEqSafeRpt','eqAccountPending','semWorkerInfo','SaSemWorkerInfoPending'].includes(to.name)
		  )) {//此处判断是如果返回上一层，你可以根据自己的业务更改此处的判断逻辑，酌情决定是否摧毁本层缓存。
            if (this.$vnode && this.$vnode.data.keepAlive) {
                if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache) {
                    if (this.$vnode.componentOptions) {
                        var key = this.$vnode.key == null
                            ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
                            : this.$vnode.key;
                        var cache = this.$vnode.parent.componentInstance.cache;
                        var keys = this.$vnode.parent.componentInstance.keys;
                        if (cache[key]) {
                            if (keys.length) {
                                var index = keys.indexOf(key);
                                if (index > -1) {
                                    keys.splice(index, 1);
                                }
                            }
                            delete cache[key];
                        }
                    }
                }
            }
            this.$destroy();
        }
        next();
    }
})
Vue.component('twoLevelOrg', twoLevelOrg)
Vue.component('companySelect', companySelect)
Vue.component('downloadButton', downloadButton)

// 打开新标签页 sessionStorage 获取不到处理
// 1.  触发标志位改变事件
window.jQuery = $;
window.$ = $;
window.localStorage.setItem('getSessionStorage', Date.now().toString())
window.addEventListener("storage", function (event) {
    if (!event.newValue) {
        return;
    }
    // 2. 监听标志位改变事件
    if (event.key === 'getSessionStorage') {
        // 3. 触发传递信息的改变事件
        let sessionInfo = {
            'Authorization': sessionStorage('token').get('Authorization'),
			'userInfo':sessionStorage('userId').getObject('userId'),
			'paramUserInfo':JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))
		}
        localStorage.setItem("sessionStorageData", JSON.stringify(sessionInfo))
        localStorage.removeItem("sessionStorageData")
    } else if (event.key === 'sessionStorageData') { // 4. 监听 传递信息 的改变事件
        // 新开启的标签页会收到这个事件
        var data = JSON.parse(event.newValue)
		if (data) {
			sessionStorage('token').set("Authorization", data['Authorization'])
			sessionStorage('userId').set('userId',JSON.stringify(data['userInfo']))
		    sessionStorage('paramUserInfo').set('userInfo', JSON.stringify(data['paramUserInfo']))
		}
    }
})



Vue.http.interceptors.push((request, next) => {
	let passtoken = sessionStorage('token').get('passAuthorization');
	if (passtoken) {//重置密码专用
		request.headers.set('Authorization', passtoken);
	}
    let token = sessionStorage('token').get('Authorization');
    if (token) {
        if (request.method === 'POST') {
            request.body = Object.assign(request.body, {appOrPc:'pc'})
        } else if (request.method === 'GET') {
            request.params = Object.assign(request.params, {appOrPc:'pc'})
        }
        request.headers.set('Authorization', token);
        request.headers.set('userId', sessionStorage('userId').getObject('userId').userId);
        request.headers.set('userName', encodeURIComponent(sessionStorage('userId').getObject('userId').userName));
        request.headers.set('loginId', sessionStorage('userId').getObject('userId').loginId);
        request.headers.set('companyId', sessionStorage('userId').getObject('userId').companyId);
        request.headers.set('companyCode', sessionStorage('userId').getObject('userId').companyCode);
        request.headers.set('companyName', encodeURIComponent(sessionStorage('userId').getObject('userId').companyName));
        request.headers.set('orgId', sessionStorage('userId').getObject('userId').orgInfo.orgId);
        request.headers.set('twoLevelOrgId', sessionStorage('userId').getObject('userId').twoLevelOrgId);
    }
  // continue to next interceptor
  //在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断，就添加在此处，页面中任何一次http请求都会先调用此处方法
    next((response) => {
        if(response.status == 401){
          sessionStorage('token').del("Authorization");
          router.replace({path:"/"});
          return response;
        }
        if(response.headers.get("authorization") != undefined){
          sessionStorage('token').set("Authorization",response.headers.get("authorization"));
        }
     //   console.log(response.header.Authorization)
     return response;
  });
});
Vue.prototype.Common = Common;
new Vue({
    store,
   router,
   render: h => h(App)
}).$mount('#app')

Vue.prototype.$Notice.config({
    top: 70,
});

